﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using wojilu.Apps.Qycms.Domain;
using wojilu.Apps.Qycms.Helper;
using wojilu.Web.Code;
using wojilu.Web.Mvc.Attr;

namespace wojilu.Web.Controller.Cn
{
    public class PublicController : BaseTempController
    {
        public PublicController()
        {
        }

        public static VerifyCode captcha
        {
            get { return new wojilu.Web.Code.VerifyCode(); }
        }

        [NonVisit]
        public virtual void Top()
        {
            view(DefaultTemp + "Public/Top");
            set("menu", loadHtml(Menu));

            SetPublic();
        }

        [NonVisit]
        public virtual void Bottom()
        {
            view(DefaultTemp + "Public/Bottom");


            SetPublic();
        }

        [NonVisit]
        public virtual void Left()
        {
            view(DefaultTemp + "Public/Left");


            SetPublic();
        }

        [NonVisit]
        public virtual void Menu()
        {
            view(DefaultTemp + "Public/Menu");

            var list = TypeList.find(" ismenu =:i").set("i", 1).list();
            bind("menulist", list);

            SetPublic();
        }

        [HttpPost]
        public virtual void MessageSave()
        {
            YBBCommon.CheckSubmit();
            var btid = ctx.PostInt("btid");
            if (CookieHelper.GetCookies("forum" + btid) != null)
            {
                ctx.web.SessionSet("errorType", 6);
                ctx.web.SessionSet("Tid", btid);
                ctx.web.SessionSet("Id", 0);
                redirect(new Cn.OtherController().CallMessage);
                return;
            }
            Bbs_TypeList bt = Bbs_TypeList.findById(btid);
            if (bt != null)
            {
                if (bt.isseccode == 1)
                {
                    captcha.CheckError(ctx);
                    if (ctx.HasErrors)
                    {
                        ctx.web.SessionSet("errorType", 2);
                        ctx.web.SessionSet("Tid", btid);
                        ctx.web.SessionSet("Id", 0);
                        redirect(new Cn.OtherController().CallMessage);
                        return;
                    }
                }
                var bbsfilter = YBBCommon.GetConfigStr("bbs_filter");
                var fcontent = ctx.Post("content");
                if (!YBBCommon.IsFilter(fcontent, bbsfilter))
                {
                    ctx.web.SessionSet("errorType", 3);
                    ctx.web.SessionSet("Tid", btid);
                    ctx.web.SessionSet("Id", 0);
                    redirect(new Cn.OtherController().CallMessage);
                    return;
                }
                bbsfilter = YBBCommon.GetConfigStr("bbs_username");
                var username = ctx.Post("username");
                var bbsusername = ctx.Post("bbsusername");
                if (!YBBCommon.IsFilter(bbsusername, bbsfilter))
                {
                    ctx.web.SessionSet("errorType", 5);
                    ctx.web.SessionSet("Tid", btid);
                    ctx.web.SessionSet("Id", 0);
                    redirect(new Cn.OtherController().CallMessage);
                    return;
                }
                var b = new Bbs();
                b.isclass = bt.isaddclass == 1 ? 0 : 1;
                b.userid = ctx.PostInt("userid");
                b.btid = ctx.PostInt("btid");
                b.upbid = 0;
                b.adminid = 0;
                b.lng = ctx.Post("lng");
                b.title = ctx.Post("title");
                b.content = fcontent;
                b.username = username;
                b.email = ctx.Post("email");
                b.qq = ctx.Post("qq");
                b.msn = ctx.Post("msn");
                b.address = ctx.Post("address");
                b.tel = ctx.Post("tel");
                b.mobile = ctx.Post("mobile");
                b.replynum = 0;
                b.click = 0;
                b.addtime = DateTime.Now;
                b.istop = 0;
                b.ipadd = ctx.Ip;
                Result result = b.insert();
                if (result.HasErrors)
                {
                    ctx.web.SessionSet("errorType", 4);
                    ctx.web.SessionSet("Tid", btid);
                    ctx.web.SessionSet("Id", 0);
                    redirect(new Cn.OtherController().CallMessage);
                    return;
                }
                else
                {
                    var inputtime = bt.inputtime;
                    if (inputtime != 0)
                    {
                        CookieHelper.SetCookie1("forum" + btid, "1", DateTime.Now.AddSeconds((int)inputtime));
                    }
                    if (bt.ismail == 1)
                    {
                        var mail = bt.putmail;
                        if (mail.StrIsNullOrEmpty())
                        {
                            mail = YBBCommon.GetConfigStr("admin_mail");
                        }
                        if (!mail.StrIsNullOrEmpty())
                        {
                            var mailcode = bt.mailcode;
                            if (mailcode.StrIsNullOrEmpty())
                            {
                                mailcode = "forumnew";
                            }
                            var bllMailSend = new YBBMailSend();
                            var dic = new Dictionary<string, object>();
                            dic["Id"] = b.Id;
                            bllMailSend.MailSend(mailcode, mail, CurrentLng, dic);
                        }
                    }
                }
            }
            else
            {
                ctx.web.SessionSet("errorType", 4);
                ctx.web.SessionSet("Tid", btid);
                ctx.web.SessionSet("Id", 0);
                redirect(new Cn.OtherController().CallMessage);
                return;
            }
        }

        [HttpPost]
        public virtual void FormSave(Int64 Id)
        {
            YBBCommon.CheckSubmit();
            if (CookieHelper.GetCookies("form" + Id) != null)
            {
                ctx.web.SessionSet("errorType", 42);
                ctx.web.SessionSet("Tid", Id);
                ctx.web.SessionSet("Id", 0);
                redirect(new Cn.OtherController().CallMessage);
                return;
            }
            Form_Group fg = Form_Group.findById(Id);
            if (fg != null)
            {
                if (fg.isseccode == 1)
                {
                    captcha.CheckError(ctx);
                    if (ctx.HasErrors)
                    {
                        ctx.web.SessionSet("errorType", 2);
                        ctx.web.SessionSet("Tid", Id);
                        ctx.web.SessionSet("Id", 0);
                        redirect(new Cn.OtherController().CallMessage);
                        return;
                    }
                }
                var fv = new Form_Value();
                fv.fgid = Id;
                fv.did = ctx.PostInt("did");
                fv.userid = ctx.PostInt("userid");
                fv.addtime = DateTime.Now;
                fv.ipadd = ctx.Ip;
                fv.isreply = 0;
                Result result = fv.insert();
                if (result.HasErrors)
                {
                    ctx.web.SessionSet("errorType", 43);
                    ctx.web.SessionSet("Tid", Id);
                    ctx.web.SessionSet("Id", 0);
                    redirect(new Cn.OtherController().CallMessage);
                    return;
                }
                else
                {
                    var sql = String.Empty;
                    foreach (var row in Form_Attr.find(" isclass =1 and fgid =" + Id).list())
                    {
                        var attrname = ctx.Post(row.attrname);
                        sql += "update ybb_form_value set " + row.attrname + " = '" + attrname + "' where Id =" +fv.Id + ";";
                    }
                    db.RunSql<Form_Attr>(sql);
                    var inputtime = fg.inputtime;
                    if (inputtime != 0)
                        CookieHelper.SetCookie1("form", "1", DateTime.Now.AddSeconds((int)inputtime));
                    if(fg.ismail==1)
                    {
                        var mail = fg.putmail;
                        if (mail.StrIsNullOrEmpty())
                        {
                            mail = Configs.find("valname=:v").set("v", "admine_mail").first().value;
                        }
                        if(!mail.StrIsNullOrEmpty())
                        {
                            var mailcode = fg.mailcode;
                            if (mailcode.StrIsNullOrEmpty())
                            {
                                mailcode = "formnewremind";
                            }
                            var bllMailSend = new YBBMailSend();
                            var dic = new Dictionary<string, object>();
                            dic["Id"] = fv.Id;
                            dic["fgid"] = fg.Id;
                            bllMailSend.MailSend(mailcode, mail, CurrentLng, dic);
                        }
                    }
                    ctx.web.SessionSet("errorType", 43);
                    ctx.web.SessionSet("Tid", Id);
                    ctx.web.SessionSet("Id", 0);
                    redirect(new Cn.OtherController().CallMessage);
                    return;
                }
            }
            else
            {
                ctx.web.SessionSet("errorType", 43);
                ctx.web.SessionSet("Tid", Id);
                ctx.web.SessionSet("Id", 0);
                redirect(new Cn.OtherController().CallMessage);
                return;
            }
        }

        [HttpGet]
        public virtual void Jump()
        {
            string text = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.QueryString[0]);
            if (!text.StartsWith("http://"))
            {
                text = "http://" + text;
            }
            //this.ctx.web.ResponseWrite(text);
            //ctx.web.ResponseEnd();
            this.ctx.web.Redirect(text);
        }

        [HttpGet]
        public virtual void Map()
        {
            view(DefaultTemp + "Public/Map");
            //标题、关键词、描述
            var Title = String.Empty;
            var Keywords = String.Empty;
            var Description = String.Empty;

            Title += YBBCommon.GetLangStr(CurrentLng, "sitename");
            Keywords = YBBCommon.GetLangStr(CurrentLng, "keyword");
            Description = YBBCommon.GetLangStr(CurrentLng, "description");

            ctx.Page.SetTitle(Title);
            ctx.Page.Keywords = Keywords;
            ctx.Page.Description = Description;
            SetPublic();
        }

        [HttpGet]
        public virtual void Browser_Redirect()
        {
            var mobilestatus = YBBCommon.GetConfigStr("is_wap").ToInt();
            //检查是否开启手机网站，如果没有不检测
            if (mobilestatus == 0)
            {
                return;
            }

            StringBuilder str = new StringBuilder();
            //读Cookie的涵数
            str.Append("function getMCookie(objName){");
            str.Append("var arrStr=document.cookie.split(\"; \");");
            str.Append("for(var i=0;i<arrStr.length;i++){");
            str.Append("var temp=arrStr[i].split(\"=\");");
            str.Append("if(temp[0]==objName){return unescape(temp[1]);}");
            str.Append("}");
            str.Append("return \"\";");
            str.Append("}");
            //检测是否移动设备访问做跳转函数
            str.Append("function browserRedirect(){");
            str.Append("var sUserAgent=navigator.userAgent.toLowerCase();");
            str.Append("var bIsIpad=sUserAgent.match(/ipad/i)==\"ipad\";");
            str.Append("var bIsIphoneOs=sUserAgent.match(/iphone os/i)==\"iphone os\";");
            str.Append("var bIsMidp=sUserAgent.match(/midp/i)==\"midp\";");
            str.Append("var bIsUc7=sUserAgent.match(/rv:1.2.3.4/i)==\"rv:1.2.3.4\";");
            str.Append("var bIsUc=sUserAgent.match(/ucweb/i)==\"ucweb\";");
            str.Append("var bIsAndroid=sUserAgent.match(/android/i)==\"android\";");
            str.Append("var bIsCE=sUserAgent.match(/windows ce/i)==\"windows ce\";");
            str.Append("var bIsWM=sUserAgent.match(/windows mobile/i)==\"windows mobile\";");
            str.Append("if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM){");
            str.Append("location.href='" + sys.Path.Root + "wap/index.aspx';");
            str.Append("}");
            str.Append("}");
            //检查当前URL是否带有m2w参数，有则说明从移动设备链接过来的
            str.Append("var pageurl=window.location.search;");
            str.Append("if(pageurl=='?m2w'){");
            str.Append("document.cookie=\"m2wcookie=\" + escape(\"1\");");
            str.Append("}");
            str.Append("if(getMCookie(\"m2wcookie\")!=\"1\") browserRedirect();");

            ctx.web.ResponseWrite(str.ToString());

        }

    }
}
